<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';

import { IconifyIcon } from '@vben/icons';

import {
  Button,
  Card,
  Col,
  DatePicker,
  Descriptions,
  DescriptionsItem,
  Divider,
  Form,
  FormItem,
  Input,
  InputNumber,
  message,
  Modal,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
  Tag,
  Textarea,
} from 'ant-design-vue';
import dayjs from 'dayjs';

import StatisticsCard from '#/components/hotel/StatisticsCard.vue';

// 合同状态枚举
enum ContractStatus {
  ACTIVE = 'active',
  DRAFT = 'draft',
  EXPIRED = 'expired',
  PENDING = 'pending',
  SIGNED = 'signed',
  TERMINATED = 'terminated',
}

// 合同状态配置
const contractStatuses = [
  { value: ContractStatus.DRAFT, label: '草稿' },
  { value: ContractStatus.PENDING, label: '待签署' },
  { value: ContractStatus.SIGNED, label: '已签署' },
  { value: ContractStatus.ACTIVE, label: '已生效' },
  { value: ContractStatus.EXPIRED, label: '已到期' },
  { value: ContractStatus.TERMINATED, label: '已终止' },
];

// 响应式数据
const loading = ref(false);
const showCreateModal = ref(false);
const showDetailModal = ref(false);
const showSignModal = ref(false);
const isEdit = ref(false);
const selectedContract = ref<any>(null);
const contractFormRef = ref();

// 搜索表单
const searchForm = reactive({
  tenantName: '',
  roomNumber: '',
  status: undefined,
  createDate: null,
});

// 合同表单
const contractForm = reactive({
  id: '',
  tenantName: '',
  tenantIdCard: '',
  tenantPhone: '',
  roomNumber: '',
  monthlyRent: null,
  deposit: null,
  startDate: null,
  endDate: null,
  paymentMethod: 'monthly',
  status: ContractStatus.DRAFT,
  terms: '',
  remarks: '',
  landlordSigned: false,
  tenantSigned: false,
});

// 签署表单
const signatureForm = reactive({
  signerName: '',
  signerIdCard: '',
  signTime: null,
  signRemarks: '',
});

// 表单验证规则
const contractRules = {
  tenantName: [{ required: true, message: '请输入租客姓名' }],
  tenantIdCard: [{ required: true, message: '请输入身份证号' }],
  tenantPhone: [{ required: true, message: '请输入联系电话' }],
  roomNumber: [{ required: true, message: '请选择房间' }],
  monthlyRent: [{ required: true, message: '请输入月租金' }],
  deposit: [{ required: true, message: '请输入押金' }],
  startDate: [{ required: true, message: '请选择开始日期' }],
  endDate: [{ required: true, message: '请选择结束日期' }],
  paymentMethod: [{ required: true, message: '请选择付款方式' }],
};

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 模拟数据
const contracts = ref([
  {
    id: '1',
    tenantName: '张三',
    tenantIdCard: '110101199001011234',
    tenantPhone: '13800138001',
    roomNumber: '101',
    monthlyRent: 3000,
    deposit: 6000,
    startDate: dayjs('2024-01-01'),
    endDate: dayjs('2024-12-31'),
    paymentMethod: 'monthly',
    status: ContractStatus.PENDING,
    terms: '标准房屋租赁合同条款...',
    remarks: '客户要求尽快入住',
    landlordSigned: true,
    tenantSigned: false,
    landlordName: '李房东',
    createdAt: dayjs('2024-01-10 10:00'),
    updatedAt: dayjs('2024-01-10 10:00'),
  },
  {
    id: '2',
    tenantName: '李四',
    tenantIdCard: '110101199002022345',
    tenantPhone: '13800138002',
    roomNumber: '201',
    monthlyRent: 4500,
    deposit: 9000,
    startDate: dayjs('2024-02-01'),
    endDate: dayjs('2025-01-31'),
    paymentMethod: 'quarterly',
    status: ContractStatus.ACTIVE,
    terms: '标准房屋租赁合同条款...',
    remarks: '季度付款',
    landlordSigned: true,
    tenantSigned: true,
    landlordName: '王房东',
    createdAt: dayjs('2024-01-15 14:30'),
    updatedAt: dayjs('2024-02-01 09:00'),
  },
  {
    id: '3',
    tenantName: '王五',
    tenantIdCard: '110101199003033456',
    tenantPhone: '13800138003',
    roomNumber: '301',
    monthlyRent: 6000,
    deposit: 12_000,
    startDate: dayjs('2023-06-01'),
    endDate: dayjs('2024-05-31'),
    paymentMethod: 'halfYearly',
    status: ContractStatus.EXPIRED,
    terms: '标准房屋租赁合同条款...',
    remarks: '半年付款',
    landlordSigned: true,
    tenantSigned: true,
    landlordName: '赵房东',
    createdAt: dayjs('2023-05-20 16:20'),
    updatedAt: dayjs('2024-05-31 23:59'),
  },
]);

// 可用房间数据
const availableRooms = ref([
  { id: '101', roomNumber: '101', type: '一室一厅' },
  { id: '102', roomNumber: '102', type: '一室一厅' },
  { id: '201', roomNumber: '201', type: '两室一厅' },
  { id: '202', roomNumber: '202', type: '两室一厅' },
  { id: '301', roomNumber: '301', type: '三室两厅' },
  { id: '302', roomNumber: '302', type: '三室两厅' },
  { id: '303', roomNumber: '303', type: '三室两厅' },
]);

// 统计信息
const statistics = computed(() => {
  const pendingCount = contracts.value.filter(
    (item) => item.status === ContractStatus.PENDING,
  ).length;
  const signedCount = contracts.value.filter(
    (item) => item.status === ContractStatus.SIGNED,
  ).length;
  const activeCount = contracts.value.filter(
    (item) => item.status === ContractStatus.ACTIVE,
  ).length;
  const expiredCount = contracts.value.filter(
    (item) => item.status === ContractStatus.EXPIRED,
  ).length;

  return {
    pendingCount,
    signedCount,
    activeCount,
    expiredCount,
  };
});

// 过滤后的合同列表
const filteredContracts = computed(() => {
  let filtered = contracts.value;

  if (searchForm.tenantName) {
    filtered = filtered.filter((item) =>
      item.tenantName.includes(searchForm.tenantName),
    );
  }

  if (searchForm.roomNumber) {
    filtered = filtered.filter((item) =>
      item.roomNumber.includes(searchForm.roomNumber),
    );
  }

  if (searchForm.status) {
    filtered = filtered.filter((item) => item.status === searchForm.status);
  }

  if (searchForm.createDate) {
    filtered = filtered.filter((item) =>
      dayjs(item.createdAt).isSame(searchForm.createDate, 'day'),
    );
  }

  return filtered;
});

// 表格列定义
const columns = [
  {
    title: '租客姓名',
    dataIndex: 'tenantName',
    key: 'tenantName',
    width: 120,
  },
  {
    title: '房间号',
    dataIndex: 'roomNumber',
    key: 'roomNumber',
    width: 100,
  },
  {
    title: '月租金',
    dataIndex: 'monthlyRent',
    key: 'monthlyRent',
    width: 100,
    customRender: ({ text }: any) => `¥${text}`,
  },
  {
    title: '租期',
    key: 'rentPeriod',
    width: 200,
    customRender: ({ record }: any) =>
      `${formatDate(record.startDate)} 至 ${formatDate(record.endDate)}`,
  },
  {
    title: '合同状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '签署状态',
    key: 'signatureStatus',
    width: 150,
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    width: 160,
    customRender: ({ text }: any) => formatDateTime(text),
  },
  {
    title: '操作',
    key: 'action',
    width: 250,
    fixed: 'right',
  },
];

// 工具函数
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    [ContractStatus.DRAFT]: 'default',
    [ContractStatus.PENDING]: 'orange',
    [ContractStatus.SIGNED]: 'blue',
    [ContractStatus.ACTIVE]: 'green',
    [ContractStatus.EXPIRED]: 'red',
    [ContractStatus.TERMINATED]: 'red',
  };
  return colorMap[status] || 'default';
};

const getStatusText = (status: string) => {
  const statusItem = contractStatuses.find((item) => item.value === status);
  return statusItem?.label || status;
};

const getPaymentMethodText = (method: string) => {
  const methodMap: Record<string, string> = {
    monthly: '月付',
    quarterly: '季付',
    halfYearly: '半年付',
    yearly: '年付',
  };
  return methodMap[method] || method;
};

const formatDate = (date: any) => {
  return date ? dayjs(date).format('YYYY-MM-DD') : '';
  datedayjs.format;
};

const formatDateTime = (datetime: any) => {
  return datetime ? dayjs(datetime).format('YYYY-MM-DD HH:mm') : '';
  datetimedayjs.format;
};

// 事件处理函数
const handleSearch = () => {
  pagination.current = 1;
};

const handleReset = () => {
  Object.assign(searchForm, {
    tenantName: '',
    roomNumber: '',
    status: undefined,
    createDate: null,
  });
  pagination.current = 1;
};

const handleView = (record: any) => {
  selectedContract.value = record;
  showDetailModal.value = true;
};

const handleEdit = (record: any) => {
  isEdit.value = true;
  Object.assign(contractForm, {
    ...record,
    startDate: dayjs(record.startDate),
    endDate: dayjs(record.endDate),
  });
  showCreateModal.value = true;
};

const handleSendForSignature = (record: any) => {
  Modal.confirm({
    title: '发起签署',
    content: `确定要发起租客 ${record.tenantName} 的合同签署吗？`,
    onOk: () => {
      const index = contracts.value.findIndex((item) => item.id === record.id);
      if (index !== -1) {
        contracts.value[index].status = ContractStatus.PENDING;
        contracts.value[index].updatedAt = dayjs();
        message.success('签署邀请已发送');
      }
    },
  });
};

const handleSign = (record: any) => {
  selectedContract.value = record;
  Object.assign(signatureForm, {
    signerName: record.tenantName,
    signerIdCard: record.tenantIdCard,
    signTime: dayjs(),
    signRemarks: '',
  });
  showSignModal.value = true;
};

const handleSignConfirm = () => {
  if (!signatureForm.signerName || !signatureForm.signerIdCard) {
    message.error('请填写完整的签署信息');
    return;
  }

  const index = contracts.value.findIndex(
    (item) => item.id === selectedContract.value.id,
  );
  if (index !== -1) {
    contracts.value[index].tenantSigned = true;
    contracts.value[index].status = ContractStatus.SIGNED;
    contracts.value[index].updatedAt = dayjs();
    message.success('签署成功');
    showSignModal.value = false;
  }
};

const handleSignCancel = () => {
  showSignModal.value = false;
  Object.assign(signatureForm, {
    signerName: '',
    signerIdCard: '',
    signTime: null,
    signRemarks: '',
  });
};

const handleActivate = (record: any) => {
  Modal.confirm({
    title: '合同生效',
    content: `确定要激活租客 ${record.tenantName} 的合同吗？`,
    onOk: () => {
      const index = contracts.value.findIndex((item) => item.id === record.id);
      if (index !== -1) {
        contracts.value[index].status = ContractStatus.ACTIVE;
        contracts.value[index].updatedAt = dayjs();
        message.success('合同已生效');
      }
    },
  });
};

const handleDownload = (record: any) => {
  message.success('合同下载中...');
  // 这里可以实现实际的下载逻辑
};

const handleDelete = (record: any) => {
  Modal.confirm({
    title: '删除合同',
    content: `确定要删除租客 ${record.tenantName} 的合同吗？`,
    onOk: () => {
      const index = contracts.value.findIndex((item) => item.id === record.id);
      if (index !== -1) {
        contracts.value.splice(index, 1);
        message.success('删除成功');
      }
    },
  });
};

const handleSave = async () => {
  try {
    await contractFormRef.value.validate();

    if (isEdit.value) {
      // 编辑模式
      const index = contracts.value.findIndex(
        (item) => item.id === contractForm.id,
      );
      if (index !== -1) {
        contracts.value[index] = {
          ...contractForm,
          updatedAt: dayjs(),
          updatedAt,
        };
        message.success('编辑成功');
      }
    } else {
      // 新增模式
      const newContract = {
        ...contractForm,
        id: Date.now().toString(),
        landlordSigned: false,
        tenantSigned: false,
        landlordName: '房东',
        createdAt: dayjs(),
        updatedAt: dayjs(),
      };
      contracts.value.unshift(newContract);
      message.success('创建成功');
    }

    handleCancel();
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

const handleCancel = () => {
  showCreateModal.value = false;
  isEdit.value = false;
  contractFormRef.value?.resetFields();
  Object.assign(contractForm, {
    id: '',
    tenantName: '',
    tenantIdCard: '',
    tenantPhone: '',
    roomNumber: '',
    monthlyRent: null,
    deposit: null,
    startDate: null,
    endDate: null,
    paymentMethod: 'monthly',
    status: ContractStatus.DRAFT,
    terms: '',
    remarks: '',
    landlordSigned: false,
    tenantSigned: false,
  });
};

// 初始化
onMounted(() => {
  // 可以在这里加载数据
});
</script>

<template>
  <div class="contract-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>电子合同管理</h2>
      <Button type="primary" @click="showCreateModal = true">
        <IconifyIcon icon="ant-design:plus-outlined" />
        创建合同
      </Button>
    </div>

    <!-- 搜索表单 -->
    <Card class="search-card">
      <Form :model="searchForm" layout="inline">
        <FormItem label="租客姓名">
          <Input
            v-model:value="searchForm.tenantName"
            placeholder="请输入租客姓名"
          />
        </FormItem>
        <FormItem label="房间号">
          <Input
            v-model:value="searchForm.roomNumber"
            placeholder="请输入房间号"
          />
        </FormItem>
        <FormItem label="合同状态">
          <Select
            v-model:value="searchForm.status"
            placeholder="请选择状态"
            style="width: 120px"
          >
            <SelectOption
              v-for="status in contractStatuses"
              :key="status.value"
              :value="status.value"
            >
              {{ status.label }}
            </SelectOption>
          </Select>
        </FormItem>
        <FormItem label="创建日期">
          <DatePicker
            v-model:value="searchForm.createDate"
            placeholder="请选择日期"
            style="width: 150px"
          />
        </FormItem>
        <FormItem>
          <Button type="primary" @click="handleSearch">
            <IconifyIcon icon="ant-design:search-outlined" />
            搜索
          </Button>
          <Button @click="handleReset" style="margin-left: 8px">
            <IconifyIcon icon="ant-design:reload-outlined" />
            重置
          </Button>
        </FormItem>
      </Form>
    </Card>

    <!-- 统计卡片 -->
    <Row :gutter="16" class="statistics-row">
      <Col :span="6">
        <StatisticsCard
          title="待签署"
          :value="statistics.pendingCount"
          prefix=""
          color="#faad14"
          icon="ant-design:clock-circle-outlined"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="已签署"
          :value="statistics.signedCount"
          prefix=""
          color="#52c41a"
          icon="ant-design:check-circle-outlined"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="已生效"
          :value="statistics.activeCount"
          prefix=""
          color="#1890ff"
          icon="ant-design:file-text-outlined"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="已到期"
          :value="statistics.expiredCount"
          prefix=""
          color="#ff4d4f"
          icon="ant-design:exclamation-circle-outlined"
        />
      </Col>
    </Row>

    <!-- 合同列表 -->
    <Card class="table-card">
      <Table
        :columns="columns"
        :data-source="filteredContracts"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <Tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'signatureStatus'">
            <Space>
              <Tag v-if="record.landlordSigned" color="green">房东已签</Tag>
              <Tag v-else color="red">房东未签</Tag>
              <Tag v-if="record.tenantSigned" color="green">租客已签</Tag>
              <Tag v-else color="red">租客未签</Tag>
            </Space>
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button type="link" size="small" @click="handleView(record)">
                查看
              </Button>
              <Button type="link" size="small" @click="handleEdit(record)">
                编辑
              </Button>
              <Button
                v-if="record.status === 'draft'"
                type="link"
                size="small"
                @click="handleSendForSignature(record)"
              >
                发起签署
              </Button>
              <Button
                v-if="record.status === 'pending'"
                type="link"
                size="small"
                @click="handleSign(record)"
              >
                签署
              </Button>
              <Button
                v-if="record.status === 'signed'"
                type="link"
                size="small"
                @click="handleActivate(record)"
              >
                生效
              </Button>
              <Button type="link" size="small" @click="handleDownload(record)">
                下载
              </Button>
              <Button
                type="link"
                size="small"
                danger
                @click="handleDelete(record)"
              >
                删除
              </Button>
            </Space>
          </template>
        </template>
      </Table>
    </Card>

    <!-- 创建/编辑合同模态框 -->
    <Modal
      v-model:open="showCreateModal"
      :title="isEdit ? '编辑合同' : '创建合同'"
      width="900px"
      @ok="handleSave"
      @cancel="handleCancel"
    >
      <Form
        ref="contractFormRef"
        :model="contractForm"
        :rules="contractRules"
        layout="vertical"
      >
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="租客姓名" name="tenantName">
              <Input
                v-model:value="contractForm.tenantName"
                placeholder="请输入租客姓名"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="租客身份证号" name="tenantIdCard">
              <Input
                v-model:value="contractForm.tenantIdCard"
                placeholder="请输入身份证号"
              />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="联系电话" name="tenantPhone">
              <Input
                v-model:value="contractForm.tenantPhone"
                placeholder="请输入联系电话"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="房间号" name="roomNumber">
              <Select
                v-model:value="contractForm.roomNumber"
                placeholder="请选择房间"
                style="width: 100%"
              >
                <SelectOption
                  v-for="room in availableRooms"
                  :key="room.id"
                  :value="room.roomNumber"
                >
                  {{ room.roomNumber }} ({{ room.type }})
                </SelectOption>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="月租金" name="monthlyRent">
              <InputNumber
                v-model:value="contractForm.monthlyRent"
                placeholder="请输入月租金"
                style="width: 100%"
                :min="0"
                :precision="2"
                addon-after="元"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="押金" name="deposit">
              <InputNumber
                v-model:value="contractForm.deposit"
                placeholder="请输入押金"
                style="width: 100%"
                :min="0"
                :precision="2"
                addon-after="元"
              />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="租期开始" name="startDate">
              <DatePicker
                v-model:value="contractForm.startDate"
                placeholder="请选择开始日期"
                style="width: 100%"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="租期结束" name="endDate">
              <DatePicker
                v-model:value="contractForm.endDate"
                placeholder="请选择结束日期"
                style="width: 100%"
              />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="付款方式" name="paymentMethod">
              <Select
                v-model:value="contractForm.paymentMethod"
                placeholder="请选择付款方式"
                style="width: 100%"
              >
                <SelectOption value="monthly">月付</SelectOption>
                <SelectOption value="quarterly">季付</SelectOption>
                <SelectOption value="halfYearly">半年付</SelectOption>
                <SelectOption value="yearly">年付</SelectOption>
              </Select>
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="合同状态" name="status">
              <Select
                v-model:value="contractForm.status"
                placeholder="请选择状态"
                style="width: 100%"
              >
                <SelectOption
                  v-for="status in contractStatuses"
                  :key="status.value"
                  :value="status.value"
                >
                  {{ status.label }}
                </SelectOption>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <FormItem label="合同条款" name="terms">
          <Textarea
            v-model:value="contractForm.terms"
            placeholder="请输入合同条款"
            :rows="6"
          />
        </FormItem>
        <FormItem label="备注" name="remarks">
          <Textarea
            v-model:value="contractForm.remarks"
            placeholder="请输入备注信息"
            :rows="2"
          />
        </FormItem>
      </Form>
    </Modal>

    <!-- 合同详情模态框 -->
    <Modal
      v-model:open="showDetailModal"
      title="合同详情"
      width="800px"
      :footer="null"
    >
      <Descriptions :column="2" bordered>
        <DescriptionsItem label="租客姓名">
          {{ selectedContract?.tenantName }}
        </DescriptionsItem>
        <DescriptionsItem label="租客身份证号">
          {{ selectedContract?.tenantIdCard }}
        </DescriptionsItem>
        <DescriptionsItem label="联系电话">
          {{ selectedContract?.tenantPhone }}
        </DescriptionsItem>
        <DescriptionsItem label="房间号">
          {{ selectedContract?.roomNumber }}
        </DescriptionsItem>
        <DescriptionsItem label="月租金">
          ¥{{ selectedContract?.monthlyRent }}
        </DescriptionsItem>
        <DescriptionsItem label="押金">
          ¥{{ selectedContract?.deposit }}
        </DescriptionsItem>
        <DescriptionsItem label="租期开始">
          {{ formatDate(selectedContract?.startDate) }}
        </DescriptionsItem>
        <DescriptionsItem label="租期结束">
          {{ formatDate(selectedContract?.endDate) }}
        </DescriptionsItem>
        <DescriptionsItem label="付款方式">
          {{ getPaymentMethodText(selectedContract?.paymentMethod) }}
        </DescriptionsItem>
        <DescriptionsItem label="合同状态">
          <Tag :color="getStatusColor(selectedContract?.status)">
            {{ getStatusText(selectedContract?.status) }}
          </Tag>
        </DescriptionsItem>
        <DescriptionsItem label="签署状态" :span="2">
          <Space>
            <Tag v-if="selectedContract?.landlordSigned" color="green">
              房东已签
            </Tag>
            <Tag v-else color="red">房东未签</Tag>
            <Tag v-if="selectedContract?.tenantSigned" color="green">
              租客已签
            </Tag>
            <Tag v-else color="red">租客未签</Tag>
          </Space>
        </DescriptionsItem>
        <DescriptionsItem label="合同条款" :span="2">
          {{ selectedContract?.terms || '无' }}
        </DescriptionsItem>
        <DescriptionsItem label="备注" :span="2">
          {{ selectedContract?.remarks || '无' }}
        </DescriptionsItem>
        <DescriptionsItem label="创建时间">
          {{ formatDateTime(selectedContract?.createdAt) }}
        </DescriptionsItem>
        <DescriptionsItem label="更新时间">
          {{ formatDateTime(selectedContract?.updatedAt) }}
        </DescriptionsItem>
      </Descriptions>
    </Modal>

    <!-- 电子签署模态框 -->
    <Modal
      v-model:open="showSignModal"
      title="电子签署"
      width="600px"
      @ok="handleSignConfirm"
      @cancel="handleSignCancel"
    >
      <div class="sign-content">
        <div class="sign-preview">
          <h4>合同预览</h4>
          <div class="contract-preview">
            <p><strong>房屋租赁合同</strong></p>
            <p>出租方：{{ selectedContract?.landlordName || '房东' }}</p>
            <p>承租方：{{ selectedContract?.tenantName }}</p>
            <p>房屋地址：{{ selectedContract?.roomNumber }}</p>
            <p>月租金：¥{{ selectedContract?.monthlyRent }}</p>
            <p>
              租期：{{ formatDate(selectedContract?.startDate) }} 至
              {{ formatDate(selectedContract?.endDate) }}
            </p>
          </div>
        </div>

        <Divider />

        <div class="signature-area">
          <h4>电子签名</h4>
          <Form :model="signatureForm" layout="vertical">
            <FormItem label="签署人姓名" name="signerName">
              <Input
                v-model:value="signatureForm.signerName"
                placeholder="请输入签署人姓名"
              />
            </FormItem>
            <FormItem label="签署人身份证号" name="signerIdCard">
              <Input
                v-model:value="signatureForm.signerIdCard"
                placeholder="请输入身份证号"
              />
            </FormItem>
            <FormItem label="签署时间" name="signTime">
              <DatePicker
                v-model:value="signatureForm.signTime"
                show-time
                placeholder="请选择签署时间"
                style="width: 100%"
              />
            </FormItem>
            <FormItem label="签署备注" name="signRemarks">
              <Textarea
                v-model:value="signatureForm.signRemarks"
                placeholder="请输入签署备注"
                :rows="2"
              />
            </FormItem>
          </Form>
        </div>
      </div>
    </Modal>
  </div>
</template>

<style scoped>
.contract-management {
  padding: 24px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  color: #1f2937;
}

.search-card {
  margin-bottom: 24px;
}

.statistics-row {
  margin-bottom: 24px;
}

.table-card {
  margin-bottom: 24px;
}

.sign-content {
  max-height: 60vh;
  overflow-y: auto;
}

.sign-preview {
  margin-bottom: 16px;
}

.contract-preview {
  padding: 16px;
  font-size: 14px;
  line-height: 1.6;
  background: #f5f5f5;
  border-radius: 6px;
}

.contract-preview p {
  margin: 4px 0;
}

.signature-area {
  margin-top: 16px;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 600;
  background-color: #fafafa;
}

:deep(.ant-form-item) {
  margin-bottom: 16px;
}

:deep(.ant-modal-body) {
  max-height: 60vh;
  overflow-y: auto;
}
</style>
